package com.sunshine.wrongquestionset.activity.question_set

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.add_question.SpinnerAdapter
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.activity.exercise.ExerciseActivity
import com.sunshine.wrongquestionset.activity.question.QuestionActivity
import com.sunshine.wrongquestionset.activity.subject_analyzer.SubjectAnalyzerActivity
import com.sunshine.wrongquestionset.callback.OnClickListener
import com.sunshine.wrongquestionset.callback.OnListEmptyListener
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.sunshine.wrongquestionset.room.entity.QuestionSetActivityBean
import com.sunshine.wrongquestionset.room.entity.QuestionSetEntity
import com.sunshine.wrongquestionset.room.entity.SubjectEntity
import com.sunshine.wrongquestionset.utils.AnalyzerUtils
import com.sunshine.wrongquestionset.utils.QuicklyExerciseBean
import kotlinx.android.synthetic.main.activity_question_set.*
import kotlinx.android.synthetic.main.activity_question_set.recyclerView
import kotlinx.android.synthetic.main.fragment_search.*

class QuestionSetActivity : BaseActivity() {

    private lateinit var viewModel: QuestionSetViewModel

    private var subjectId = -1
    private var subjectName = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_question_set)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(QuestionSetViewModel::class.java)

        subjectId = intent.getIntExtra("subjectId", -1)
        val intentSubjectName = intent.getStringExtra("subjectName")
        subjectName = if(intentSubjectName == null) {
            //设置标题
            setTitle("我的错题本")
            //隐藏单科练习，因为此时只为查看所有错题本，而没有指定某一科
            include_subject_exercise.visibility = View.GONE
            divider.visibility = View.GONE

            getString(R.string.label_question_set)
        } else {
            setTitle("科目：${intentSubjectName}")
            intentSubjectName
        }

        viewModel.getQuestionActivityBeanList(getLoginUserId(), subjectId).observe(this, Observer {list ->

            recyclerView.setLayoutManager(LinearLayoutManager(this))

            val adapter = QuestionSetAdapter(
                list as ArrayList<QuestionSetActivityBean>,
                getLoginUserAppConfig(),
                viewModel,
                this,
                //处理item点击回调，点击直接进入，长按功能菜单
                object : OnClickListener {
                    override fun onClick(position: Int) {
                        val intent = Intent(this@QuestionSetActivity, QuestionActivity::class.java)
                        intent.putExtra("type", QuestionActivity.TYPE_QUESTION_SET)
                        intent.putExtra("subjectId", list[position].subjectId)
                        intent.putExtra("setId", list[position].id)
                        startActivity(intent)
                    }

                    override fun onLongClick(position: Int) {
                        //将当前的科目信息传递给全局变量，这样，spinner默认展示的就是当前科目了
                        subjectId = list[position].id
                        val builder = MaterialAlertDialogBuilder(this@QuestionSetActivity)

                        var dialog: AlertDialog? = null

                        builder.apply {
                            val menuView = LayoutInflater.from(this@QuestionSetActivity).inflate(R.layout.view_question_set_menu, null, false)
                            val show: MaterialButton = menuView.findViewById(R.id.button_show)
                            //val toDefault: MaterialButton = menuView.findViewById(R.id.button_to_default)
                            val edit: MaterialButton = menuView.findViewById(R.id.button_edit)
                            val toDelete: MaterialButton = menuView.findViewById(R.id.button_to_delete)

                            show.setOnClickListener {
                                val intent = Intent(this@QuestionSetActivity, QuestionActivity::class.java)
                                intent.putExtra("type", QuestionActivity.TYPE_QUESTION_SET)
                                intent.putExtra("subjectId", subjectId)
                                intent.putExtra("setId", list[position].id)
                                startActivity(intent)
                                dialog?.cancel()
                            }
//                            toDefault.setOnClickListener {
//                                //为了刷新迫不得已
//                                getLoginUserAppConfig()?.nowQuestionSetId = list[position].id
//                                updateAppConfig(null)
//                                viewModel.updateQuestionSet(list[position])
//                                viewModel.setDefault(getLoginUserId(), list[position].id)
//                                Snackbar.make(question_set_root, getString(R.string.to_default_success), Snackbar.LENGTH_SHORT).show()
//                                dialog?.cancel()
//                            }
                            edit.setOnClickListener {
                                dialog?.cancel()
                                editQuestionSet(list[position])
                            }
                            toDelete.setOnClickListener {
//                                if (list[position].id == getLoginUserAppConfig()?.nowQuestionSetId) {
//                                    Snackbar.make(question_set_root, getString(R.string.delete_fail), Snackbar.LENGTH_SHORT).show()
//                                } else {
//                                    viewModel.toDelete(list[position])
//                                    Snackbar.make(question_set_root, getString(R.string.delete_success), Snackbar.LENGTH_SHORT).show()
//                                }
                                viewModel.toDelete(list[position])
                                Snackbar.make(question_set_root, getString(R.string.delete_success), Snackbar.LENGTH_SHORT).show()
                                dialog?.cancel()
                            }
                            setView(menuView)
                        }
                        dialog = builder.create()
                        dialog.show()
                    }
                }
            )
//            adapter.addListEmptyListener(object : OnListEmptyListener {
//                override fun isEmpty(empty: Boolean) {
//                    imageView_empty.visibility = if (empty) View.VISIBLE else View.GONE
//                }
//            })

            recyclerView.setAdapter(adapter)
        })

        val questionBySubjectLiveData = viewModel.getQuestionBySubjectId(subjectId)

        questionBySubjectLiveData.observe(this, Observer {questionList ->
            val hashMap = HashMap<Int, ArrayList<QuestionEntity>>()
            hashMap[subjectId] = questionList as ArrayList<QuestionEntity>
            val quicklyExerciseBean: QuicklyExerciseBean? = AnalyzerUtils.getBestQuicklyExerciseSubject(hashMap)
            //推荐题目
            include_subject_exercise.setOnClickListener {
                if (quicklyExerciseBean == null || quicklyExerciseBean.questionList.isNullOrEmpty()) {
                    Snackbar.make(question_set_root, getString(R.string.quickly_exercise_fail), Snackbar.LENGTH_SHORT).show()
                }
                else {
//                    //按照熟悉程度排序
//                    val sortQuestionList = AnalyzerUtils.sortQuestionListByFamiliarity(questionList)
                    ExerciseActivity.subjectName = subjectName
                    ExerciseActivity.setQuestionList(quicklyExerciseBean.questionList)
                    startActivity(Intent(this, ExerciseActivity::class.java))
                }
            }
        })

        fab_add_question_set.setOnClickListener {
            addQuestionSet()
        }
    }

    /**
     * 添加错题本
     */
    private fun addQuestionSet() {
        editQuestionSet(null)
    }

    /**
     * 修改错题本信息
     * @param questionSetEntity 错题集实体类
     */
    private fun editQuestionSet(questionSetBean: QuestionSetActivityBean?) {
        val builder = MaterialAlertDialogBuilder(this)
        builder.apply {
            val view = LayoutInflater.from(this@QuestionSetActivity).inflate(R.layout.view_add_question_set, null, false)
            val nameEditText: TextInputEditText = view.findViewById(R.id.edit_add_question_set_name)
            val descriptionEditText: TextInputEditText = view.findViewById(R.id.edit_add_question_set_description)
            val includeSubject: View = view.findViewById(R.id.include_subject)
            val spinnerText: TextView = includeSubject.findViewById(R.id.textView_spinner)
            val spinner: Spinner = includeSubject.findViewById(R.id.spinner)

            //编辑模式填充内容
            nameEditText.setText(questionSetBean?.name)
            descriptionEditText.setText(questionSetBean?.description)

            //填充spinnerView
            spinnerText.text = "所属科目"
            viewModel.getSubjectByUserId(getLoginUserId()).observe(this@QuestionSetActivity, Observer {
                spinner.adapter = SpinnerAdapter(
                    this@QuestionSetActivity,
                    R.layout.view_spinner_item,
                    R.id.textView_spinner_item,
                    it?.toMutableList()?:ArrayList<SubjectEntity>().toMutableList(),
                    SpinnerAdapter.TYPE_SUBJECT
                )

                //设置默认选择的科目，因为上次或者首次进入，用户可能有希望的选择
                if (it != null) {
                    for (i in it.indices) {
                        if (it[i].id == subjectId) {
                            spinner.setSelection(i, true)
                            break
                        }
                    }
                }

                spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                    override fun onNothingSelected(parent: AdapterView<*>?) {

                    }

                    override fun onItemSelected(
                        parent: AdapterView<*>?,
                        view: View?,
                        position: Int,
                        id: Long
                    ) {
                        //切换后更新科目类型
                        subjectId = id.toInt()
                    }
                }
            })

            setView(view)
            setTitle(getString(R.string.add_question_set))
            setPositiveButton("确定") {_, _ ->
                val name0 = nameEditText.text?.toString()
                val description0 = descriptionEditText.text?.toString()
                if (name0.isNullOrBlank()) {
                    Snackbar.make(question_set_root, getString(R.string.question_set_error), Snackbar.LENGTH_SHORT).show()
                } else {
                    //添加模式
                    if (questionSetBean == null) {
                        //TODO 背景颜色支持
                        viewModel.addQuestionSet(getLoginUserId(), name0, description0, subjectId, "#8AB4F8")
                        Snackbar.make(question_set_root, getString(R.string.add_question_set_success), Snackbar.LENGTH_SHORT).show()
                    }
                    //编辑模式
                    else {
                        questionSetBean.name = name0
                        questionSetBean.description = description0
                        questionSetBean.subjectId = subjectId
                        //TODO 背景颜色更改

                        viewModel.updateQuestionSet(questionSetBean)
                        Snackbar.make(question_set_root, getString(R.string.edit_question_set_success), Snackbar.LENGTH_SHORT).show()
                    }
                }
            }
        }
        builder.create().show()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        //如果不是所有科目，就是从主界面点击进入的单科错题集，即可显示分析
        if (subjectId != -1) menuInflater.inflate(R.menu.menu_question_set, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.analyzer -> {
                val intent = Intent(this, SubjectAnalyzerActivity::class.java)
                intent.putExtra("subjectId", subjectId)
                intent.putExtra("subjectName", subjectName)
                startActivity(intent)
            }
        }
        return super.onOptionsItemSelected(item)
    }

    companion object {
        private const val TAG = "QuestionSetActivity"
    }
}